﻿using ViewMaker.Core;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Windows.Input;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace ViewMaker.Core.Tests
{
    [TestClass()]
    public class ViewModelTest
    {
        public class TestViewModel : ViewModelBase
        {
            [Required(ErrorMessage = "Inputは必須")]
            public string Input
            {
                get { return _input; }
                set { ValidateProperty("Input", value); _input = value; }
            }
            public string _input;

            public string Output
            {
                get { return _output; }
                set { _output = value; OnPropertyChanged("Output"); }
            }
            private string _output;

            public ICommand TestCommand
            {
                get { return CreateCommand(TestAction); }
            }

            public void TestAction()
            {
                if (!Validate()) return;
                Output = "Test:" + Input;
            }
        }

        [TestMethod()]
        public void ViewModelアクションの実行()
        {
            string changed = null;
            var target = new TestViewModel();
            target.Input = "Hello";
            target.PropertyChanged += delegate(object sender, PropertyChangedEventArgs arg) { changed = arg.PropertyName; };
            Assert.AreEqual(true, ((ICommand)target.TestCommand).CanExecute(null));
            target.TestCommand.Execute(null);

            Assert.AreEqual("Test:Hello", target.Output);
            Assert.AreEqual("Output", changed);
        }

        [TestMethod()]
        public void ViewModel検証の実行()
        {
            bool validated = false;
            var target = new TestViewModel();
            try
            {
                target.Input = null;
                Assert.Fail("検証エラーが発生しない");
            }
            catch (ValidationException ex)
            {
                Assert.AreEqual("Inputは必須", ex.Message);
            }
            target.ViewCommandNotified += delegate(object sender, ViewCommandEventArgs arg) 
                                            { if (arg.Command == ViewCommands.Validate) validated = true; };
            target.TestCommand.Execute(null);

            Assert.AreEqual(true, validated);
        }
    }
}
